import {
	local,
	dev,
	prod
} from "./env.js"

// 发布时，记得同时修改baseUrl
const baseUrl = local.baseUrl;

import {
	getToken,
	setToken,
	removeToken,
	removeUserInfo,
	clearStorage,
} from './localStorage.js';

// 接口白名单 不使用token的接口
const whiteList = [];

// request请求封装
const request = async (subUrl, method, params = {}) => {
	const defaults = {
		header: {
			"Content-Type": "application/json",
			"Authorization": `Bearer ${getToken()}`,
		},
		method,
		data: {}
	};

	// 白名单不加token
	const flag = whiteList.some(item => subUrl.includes(item))
	if (flag) {
		delete defaults.header.Authorization;
	}
	if (!getToken()) {
		delete defaults.header.Authorization;
	}

	// 合并传过来的参数
	const options = Object.assign({}, defaults, params);
	// 返回结果
	let res = await new Promise((resolve, reject) => {
		let url = baseUrl + subUrl;

		const {
			header,
			method,
			data,
		} = options;

		uni.request({
			url,
			header,
			method,
			data,
			success: function(res) {
				const {
					status,
					msg,
				} = res.data;

				if (status === 200) {
					resolve(res.data);
				} else if (msg === 'token已失效') {
					removeToken();
					removeUserInfo();

					// 重定向页面
					uni.navigateTo({
						url: "/pages/login/login"
					});
				} else {
					uni.showToast({
						title: msg,
						icon: 'error',
						mask: true,
						duration: 3000,
					});
					reject(res.data);
				}
			},
			fail: err => {
				reject(err);
			}
		})
	})
	return res;
}

export const requestGet = (subUrl, params = {}) => {
	return request(subUrl, 'GET', params);
}

export const requestPost = (subUrl, params = {}) => {
	return request(subUrl, 'POST', params);
}

export const asyncRequestGet = async (subUrl, params = {}) => {
	try {
		return await request(subUrl, 'GET', params);
	} catch (e) {
		return false;
	}
}

export const asyncRequestPost = async (subUrl, params = {}) => {
	try {
		return await request(subUrl, 'POST', params);
	} catch (e) {
		return false;
	}
}